package controllers;

import helpers.CrawlerHelper;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import services.Blogger;

import models.AutoSite;
import models.Blog;
import models.MessageQueue;
import models.News;

import data.AutoSiteData;
import data.BlogData;
import data.MessageQueueData;
import debugs.AutoSiteDebug;
import debugs.NewsDebug;

public class CrawlerNews extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		
		MessageQueue mq = MessageQueueData.getMessageQueueForCrawler();
		
		if (mq != null) {
			AutoSite autoSite = AutoSiteData.getById(mq.getAutoSiteId());
			News news = CrawlerHelper.getNews(URLDecoder.decode(mq.getUrl()), autoSite);
			//NewsDebug.debug(news);
			
			//update isDone is true in messageQueue
			mq.setIsDone(true);
			MessageQueueData.insert(mq);
			
			//Post news to blogger
			Blog blog = BlogData.getById(autoSite.getBlogId());
			Blogger blogger = new Blogger(blog);
			try {
				blogger.createPost(news);
			} catch (Exception e) {
				e.printStackTrace();
			}
			response.setContentType("text/html");
			NewsDebug.debugWeb(news, response);
			response.getWriter().println("Update success");
			
		}
		
	}
}
